package com.flow.service.provider.toleration.apply.consumer;

import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.type.TypeReference;
import com.flow.framework.core.system.initialization.ProxyManager;
import com.flow.framework.core.system.initialization.ProxyService;
import com.flow.framework.mq.consumer.IConsumer;
import com.flow.framework.mq.pojo.bo.QueueBo;
import com.flow.service.facade.experiment.apply.pojo.dto.notify.ApplyApprovalNotifyDto;
import com.flow.service.provider.toleration.apply.service.IResourceApplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 电脑审批通过通知消费者
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2023/5/13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ComputerApprovalNotifyConsumer implements IConsumer<ApplyApprovalNotifyDto> {

    private static final QueueBo QUEUE_BO = QueueBo.build("toleration:experiment:apply",
            "toleration:experiment:apply_approval_notify");

    private static final TypeReference<ApplyApprovalNotifyDto> MESSAGE_TYPE = new TypeReference<ApplyApprovalNotifyDto>() {
    };

    private static final ProxyService<String, IResourceApplyService> PROXY_MANAGER = ProxyManager.proxy(IResourceApplyService.class);

    /**
     * 当收到消息时会调用该方法
     *
     * @param messageId 消息id
     * @param headers   headers
     * @param dto       消息内容
     */
    @Override
    public void onMessage(String messageId, Map<String, Object> headers, ApplyApprovalNotifyDto dto) {
        String applyType = dto.getApplyType();
        IResourceApplyService resourceApplyService = PROXY_MANAGER.typeOptional(applyType).orElseThrow(() -> {
            log.error("can't find service. apply type : {}, apply no : {}", applyType, dto.getApplyNo());
            return new CheckedException(SystemErrorCode.SYSTEM_NOT_SUPPORT_ERROR);
        });
        resourceApplyService.applyResultCallback(applyType, dto.isPass(), dto.getResourceId());
    }

    /**
     * 获取队列信息
     *
     * @return 队列信息
     */
    @Override
    public QueueBo getQueueBo() {
        return QUEUE_BO;
    }

    /**
     * 获取消息类型
     *
     * @return 消息类型引用
     */
    @Override
    public TypeReference<ApplyApprovalNotifyDto> getMessageType() {
        return MESSAGE_TYPE;
    }
}